<template>
  <el-dialog v-model="dialogVisible" @close="handleDialogClose(ruleFormRef)"
    :title="dialogOperateName === 'add' ? '添加模板' : '编辑模板'" width="500">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto"
      class="demo-ruleForm">
      <el-form-item label="项目ID" prop="appid">
        <el-input v-model.number="ruleForm.appid" />
      </el-form-item>
      <el-form-item label="Word代码" prop="code">
        <el-input v-model="ruleForm.code" autocomplete="off" />
      </el-form-item>
      <el-form-item label="下载名称" prop="downloadName">
        <el-input v-model="ruleForm.downloadName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="请求数据地址" prop="url">
        <el-input v-model.number="ruleForm.url" />
      </el-form-item>
      <el-form-item label="模板" prop="file" style="margin-bottom: 0; padding-bottom: 0; height: 26px"
        v-if="dialogOperateName === 'add'">
        <div class="dialog-wrapper">
          <div class="file-upload__wrapper">
            <form id="file-form">
              <input type="file" name="" class="file-upload__input" id="my-file-upload" size="28" @change="handleChange"
                ref="fileInputRef" />
            </form>
            <div class="file-upload__name" ref="fileUploadNameRef"></div>
            <label for="my-file-upload" class="file-upload__label">选择文件</label>
          </div>
        </div>
      </el-form-item>
      <el-form-item label=" ">
        <div class="file-upload-tips">{{ fileUploadTips }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { fetchTemplateData } from "@/api/get-data.js";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

let dialogOperateName = ref("add");
let dialogVisible = ref(false);
let currentUUID = ref("");

const fileInputRef = ref<HTMLInputElement | null>(null);
const fileUploadNameRef = ref<HTMLDivElement | null>(null);
let fileUploadTips = ref("");

// 文件选择相关
const checkWordType = (word) => {
  const index = word.lastIndexOf(".");
  return word.substring(index);
};

const handleChange = () => {
  const file = fileInputRef.value.files[0];
  console.log("file：");
  console.log(file);
  if (file) {
    const fileType = checkWordType(file.name);
    if (fileType.indexOf(".doc") < 0 || fileType.indexOf(".docx") < 0) {
      fileUploadTips.value = "只能选择.docx/doc类型模板文件";
      fileUploadNameRef.value.textContent = "";
      document.getElementById("file-form").reset();
      const file = fileInputRef.value.files[0];
      console.log("file：");
      console.log(file);
      return;
    }
    fileUploadTips.value = "";
    fileUploadNameRef.value.textContent = file.name;
  } else {
    fileUploadTips.value = "请选择Word模板文件";
    fileUploadNameRef.value.textContent = "";
  }
};

// 表单验证相关
const ruleFormRef = ref();
const ruleForm = reactive({
  downloadName: "",
  code: "",
  appid: "",
  url: "",
  file: "file",
});

const validateURL = (rule, value, callback) => {
  const regex = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/; // 用户名正则，4到16位字母、数字、下划线、连字符
  if (!regex.test(value)) {
    callback(new Error("请输入有效的URL地址"));
  } else {
    callback();
  }
};

const rules = reactive({
  downloadName: [
    { required: true, message: "下载名称不能为空", trigger: "blur" },
  ],
  code: [{ required: true, message: "CODE不能为空", trigger: "blur" }],
  appid: [{ required: true, message: "APPID不能为空", trigger: "blur" }],
  url: [
    { required: true, message: "URL不能为空", trigger: "blur" },
    { validator: validateURL, trigger: "blur" },
  ],
  file: [{ required: true, message: "模板不能为空", trigger: "blur" }],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  let url, message;
  const formData = new FormData();
  if (dialogOperateName.value === "add") {
    url = "/WordTool/word/maintain/form";
    formData.append("appid", ruleForm.appid);
    formData.append("code", ruleForm.code);
    formData.append("downloadName", ruleForm.downloadName);
    formData.append("url", ruleForm.url);
    formData.append("wordFile", fileInputRef.value.files[0]);

    message = "模板添加成功";
  } else if (dialogOperateName.value === "edit") {
    url = "/WordTool/word/maintain/update";
    formData.append("appid", ruleForm.appid);
    formData.append("code", ruleForm.code);
    formData.append("downloadName", ruleForm.downloadName);
    formData.append("url", ruleForm.url);
    formData.append("uuid", currentUUID.value);

    message = "模板修改成功";
  }
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");

      if (dialogOperateName.value === "add") {
        const file = fileInputRef.value.files[0];
        console.log("file");
        console.log(file);

        if (!file) {
          fileUploadTips.value = "请选择Word模板文件";
          return;
        } else if (
          file.name.indexOf(".doc") < 0 ||
          file.name.indexOf(".docx") < 0
        ) {
          fileUploadTips.value = "只能选择.docx/doc类型模板文件";
          return;
        }

        fileUploadTips.value = "";
      }

      // begin
      axios
        .post(url, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(
          (resp) => {
            if (resp.data.status === "OK") {
              ElMessage({
                message,
                type: "success",
              });

              formEl.resetFields();
              dialogVisible.value = false;
              fetchTemplateData(
                mapStore.templateTableCurrentPage,
                mapStore.templateTablePageSize
              );
            } else {
              ElMessage({
                message: resp.data.message,
                type: "error",
              });
            }
          },
          (err) => {
            console.log(err);
            ElMessage({
              message: JSON.stringify(err),
              type: "error",
            });
          }
        );
      // end
    } else {
      console.log("error submit!");
      if (dialogOperateName.value === "add") {
        const file = fileInputRef.value.files[0];
        console.log("file");
        console.log(file);

        if (!file) {
          fileUploadTips.value = "请选择Word模板文件";
          return;
        } else if (
          file.name.indexOf(".doc") < 0 ||
          file.name.indexOf(".docx") < 0
        ) {
          fileUploadTips.value = "只能选择.docx/doc类型模板文件";
          return;
        }

        fileUploadTips.value = "";
      }
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};

const handleDialogClose = (formEl) => {
  if (dialogOperateName.value === "add") {
    console.log("关闭弹窗时清空file：");
    console.log(fileInputRef.value.files[0]);
    //   fileInputRef.value.files[0].value = "";
    document.getElementById("file-form").reset();
    fileUploadTips.value = "";
    fileUploadNameRef.value.textContent = "";
  }
  dialogVisible.value = false;
  if (!formEl) return;
  formEl.resetFields();
  for (const prop in ruleForm) {
    if (ruleForm.hasOwnProperty(prop) & (prop !== "file")) {
      ruleForm[prop] = "";
    }
  }
};

defineExpose({
  dialogOperateName,
  ruleForm,
  dialogVisible,
  currentUUID,
});
</script>
<style scoped>
.dialog-wrapper {
  display: flex;
  height: auto;
  padding-bottom: 20px;
  width: 100%;
}

.file-upload__wrapper {
  flex: 1;
  border: 1px solid #dcdfe6;
  height: 31px;
  display: flex;
  border-top-left-radius: 3px;
  border-bottom-left-radius: 3px;
}

.file-upload__input {
  display: none;
}

.file-upload__label {
  display: block;
  padding: 5px 10px;
  height: 31px;
  line-height: 20px;
  background-color: #339933;
  color: white;
  cursor: pointer;
}

.file-upload__label:hover {
  background-color: #33cc00;
}

.file-upload__name {
  flex: 1;
  line-height: 30px;
  font-size: 14px;
}

.file-upload-tips {
  color: #f56c6c;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
}
</style>